package com.talkweb.ncfw.security.springsecurity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.talkweb.ncfw.component.rights.entity.Role;
import com.talkweb.ncfw.component.rights.entity.User;
import com.talkweb.ncfw.component.rights.service.ILoginManager;
import com.talkweb.ncfw.exceptions.BizBaseException;
import com.talkweb.ncfw.utils.ObjectUtils;

public class MyUserDetailsService implements UserDetailsService {
	private static final Log log = LogFactory.getLog(MyUserDetailsService.class);
	private ILoginManager loginManager;
	
	public ILoginManager getLoginManager() {
		return loginManager;
	}

	public void setLoginManager(ILoginManager loginManager) {
		this.loginManager = loginManager;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = null;
		try {
			user = this.loginManager.getLoginUser(username, ILoginManager.AuthType.LOGINID);
		} catch (BizBaseException e) {
			log.error("excute loadUserByUsername:MyUserDetailsService", e);
			return null;
		}
		List<Role> roleList = null;
		try {
			roleList = this.loginManager.findAuthorities(user.getUserId());
		} catch (BizBaseException e) {
			log.error("excute loadUserByUsername:MyUserDetailsService", e);
			return null;
		}
		/** 角色权限 */
	    Collection<GrantedAuthority> authorities = null;
	    String[] roles = null;
	    if (CollectionUtils.isNotEmpty(roleList)) {
	    	authorities = new ArrayList<GrantedAuthority>(roleList.size());
	    	roles = new String[roleList.size()];
	    	int index = 0;
	    	for (Role role : roleList) {
	    		GrantedAuthority authority = new RoleGrantedAuthority(role.getUserroleId().toString(), role.getUserroleName());
	    		authorities.add(authority);
	    		roles[index++] = ObjectUtils.toString(role.getUserroleId());
	    	}
	    }
		UserSession userSession = new UserSession(username, "", true, true,
				true, true, authorities);
		/** 初始化用户session信息 */
		userSession.init(user.getUserId(), roles, username, user.getUserName(), 
				user.getMailAddr(), user.getMobilePhone(), SpringSecurityUtils.getCurrentUserIp(), null);
		return userSession;
	}

}
